package com.shaoyu.tools.testcase.event;

import com.alibaba.fastjson.JSON;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.google.common.eventbus.SubscriberExceptionContext;

import com.shaoyu.tools.event.core.CustomSubscribeExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author shaoyu
 * @date 2022/11/8 10:31
 */
@Service
public class GlobalEventConfig implements CustomSubscribeExceptionHandler<Object> {

    Logger logger = LoggerFactory.getLogger(GlobalEventConfig.class);

    @Override
    public void handleException(Throwable throwable, SubscriberExceptionContext subscriberExceptionContext) {
        logger.error("事件异常:订阅者:"+ subscriberExceptionContext.getSubscriber().getClass().getName());
        logger.error("事件异常:订阅方法:"+ subscriberExceptionContext.getSubscriberMethod().getName());
        logger.error("事件异常",throwable);
    }

    AtomicInteger n = new AtomicInteger(0);

    @Subscribe
    @AllowConcurrentEvents
    public void receiveEvent(Object object){
        logger.info("收到事件信息:"+JSON.toJSONString(object));
        logger.info("已处理事件数量:"+n.incrementAndGet());
    }
}
